package com.macro.mall.run;

import com.macro.mall.mapper.UmsAdminMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsAdminExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class InitPasswordRunner implements ApplicationRunner {

    private final Logger logger = LoggerFactory.getLogger(InitPasswordRunner.class);

    @Autowired
    private UmsAdminMapper adminMapper;

    private final List<String> initNames = Arrays.asList("admin", "test");

    @Override
    public void run(ApplicationArguments args) throws Exception {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        UmsAdminExample example = new UmsAdminExample();
        UmsAdminExample.Criteria criteria = example.createCriteria();
        List<UmsAdmin> umsAdmins = adminMapper.selectByExample(example);
        for (UmsAdmin umsAdmin : umsAdmins) {
            if (initNames.contains(umsAdmin.getUsername())) {
                UmsAdmin update = new UmsAdmin();
                update.setId(umsAdmin.getId());
                update.setPassword(bCryptPasswordEncoder.encode("123456"));
                int i = adminMapper.updateByPrimaryKeySelective(update);
                logger.info("update password success {}, {}", umsAdmin.getNickName(), i);
            }
        }
    }
}
